package com.googlecode.genproject.model;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.googlecode.genproject.model.basic.XmlObject;

/**
 * 系统类配置信息
 * @author devilishking
 *
 */
public class ServiceConfigXml extends XmlObject<ServiceConfigXml> {
	private static final long serialVersionUID = 1L;
	private String id;							 //类标识
	private Map<String, List<String[]>> beanMap; //实体类信息集合

	public ServiceConfigXml(){
		beanMap = new HashMap<String, List<String[]>>();
	}
	
	//region 标签
	/**
	 * 标签：类
	 */
	public static final String TAG_SERVER = "server";
	/**
	 * 标签：实体类
	 */
	public static final String TAG_BEAN = "bean";
	/**
	 * 标签：版本号
	 */
	public static final String TAG_VERSION = "version";
	/**
	 * 标签：编号
	 */
	public static final String TAG_ID = "id";
	/**
	 * 标签：值
	 */
	public static final String TAG_VALUE = "value";
	//endregion
	
	//region 字典
	//region 类标识
	/**
	 * 类标识：主类
	 */
	public static final String ID_MAIN = "main";
	/**
	 * 类标识：生成项目文件
	 */
	public static final String ID_GENPROJECT = "genPrject";
	//endregion
	
	//region 实体类标识
	/**
	 * 实体类标识：默认
	 */
	public static final String BEAN_ID_DEFAULT = "default";
	//endregion
	//endregion
	
	//region 属性GET、SET方法
	/**
	 * 获取类标识
	 */
	public String getId() {
		return id;
	}
	/**
	 * 设置类标识
	 */
	public void setId(String id) {
		this.id = id;
	}
	/**
	 * 获取实体类信息集合
	 */
	public Map<String, List<String[]>> getBeanMap() {
		return beanMap;
	}
	/**
	 * 设置实体类信息集合
	 */
	public void setBeanMap(Map<String, List<String[]>> serviceMap) {
		this.beanMap = serviceMap;
	}
	//endregion
	
	//region 其它方法
	/**
	 * 初始化方式获得对象集合
	 */
	public static Map<String, ServiceConfigXml> init() throws Exception{
		Map<String, ServiceConfigXml> serviceConfigMap = new HashMap<String, ServiceConfigXml>();
		InputStream in = ClassLoader.getSystemResourceAsStream("serviceConfig.xml");
		if (in != null){
			try{
				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();    
				DocumentBuilder db = dbf.newDocumentBuilder();
				Document doc = db.parse(in);
				NodeList serversNodeList = doc.getElementsByTagName(TAG_SERVER);
				for(int i = 0; i < serversNodeList.getLength(); i++){
					ServiceConfigXml serviceConfig = new ServiceConfigXml();
					Node serverNode = serversNodeList.item(i);
					String id = serverNode.getAttributes().getNamedItem(TAG_ID).getNodeValue();
					serviceConfig.setId(id);					
					NodeList beanNodeList = serverNode.getChildNodes();
					Map<String, List<String[]>> beanMap = new HashMap<String, List<String[]>>();
					for(int j = 0; j < beanNodeList.getLength(); j++){
						Node beanNode = beanNodeList.item(j);
						String beanNodeName = beanNode.getNodeName();
						if (TAG_BEAN.equals(beanNodeName)){
							String beanId = beanNode.getAttributes().getNamedItem(TAG_ID).getNodeValue();
							NodeList versionNodeList = beanNode.getChildNodes();
							List<String[]> versionList = new ArrayList<String[]>();
							for(int k = 0; k < versionNodeList.getLength(); k++){
								Node versionNode = versionNodeList.item(k);
								String versionNodeName = versionNode.getNodeName();
								if (TAG_VERSION.equals(versionNodeName)){
									String versionId = versionNode.getAttributes().getNamedItem(TAG_ID).getNodeValue();
									String value = versionNode.getAttributes().getNamedItem(TAG_VALUE).getNodeValue();
									versionList.add(new String[]{ versionId, value });
								}
							}
							beanMap.put(beanId, versionList);
						}
					}
					serviceConfig.setBeanMap(beanMap);
					serviceConfigMap.put(id, serviceConfig);
				}
			}
			finally{
				in.close();
			}
		}
		else{
			throw new Exception(String.format("%0$s文件不存在!", "serviceConfig.xml"));
		}
		return serviceConfigMap;
	}
	
	public String toString(){
		StringBuffer str = new StringBuffer();
		str.append("[\r\n")
		   .append(" ").append(TAG_ID).append(": ").append(id);
		if (!beanMap.isEmpty()){
			Iterator<Entry<String,List<String[]>>>  it = beanMap.entrySet().iterator();
			while(it.hasNext()){
				Entry<String,List<String[]>> entry = it.next();
				str.append(",\r\n ").append(TAG_BEAN).append(": [\r\n")
				   .append(" ").append(TAG_ID).append(": ").append(entry.getKey());
				for(String[] versions : entry.getValue()){
					str.append(",\r\n   ").append(TAG_VERSION).append(": [\r\n")
					   .append("    ").append(TAG_ID).append(": ").append(versions[0])
					   .append(", ").append(TAG_VALUE).append(": ").append(versions[1])
					   .append("\r\n   ]");
				}
				str.append("\r\n ]");
			}
		}
		str.append("\r\n]");	
		return str.toString();
	}
	//endregion
}